package com.yxplearn.mybatisplus.mybatisplus_simple.type_handler;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public abstract class AbstractCollectionTypeHandler<T> extends BaseTypeHandler<T> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, parseToString(parameter));
    }

    @Override
    public T getNullableResult(ResultSet rs, String columnName) throws SQLException {
        final String stringValue = rs.getString(columnName);
        return StringUtils.isBlank(stringValue) ? null : parseToCollection(stringValue);
    }

    @Override
    public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        final String stringValue = rs.getString(columnIndex);
        return StringUtils.isBlank(stringValue) ? null : parseToCollection(stringValue);
    }

    @Override
    public T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        final String stringValue = cs.getString(columnIndex);
        return StringUtils.isBlank(stringValue) ? null : parseToCollection(stringValue);
    }

    /**
     * 数据库中字符串转集合
     */
    public abstract T parseToCollection(String value);

    /**
     * 数据库中字符串转集合
     */
    public abstract String parseToString(T collection);


}
